package com.promise.jokerdream.user

import android.util.Log
import com.promise.jokerdream.database.account.UserInfo
import com.promise.jokerdream.network.HttpHelper
import com.promise.jokerdream.network.IHttpCallback
import com.promise.jokerdream.network.HttpApiConstants
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import okhttp3.Call
import okhttp3.Response
import java.io.IOException

/**
 * 用户信息管理器
 * 负责获取和管理用户信息
 * 使用单例模式确保全局唯一实例
 */
object UserInfoManager {

    /**
     * 获取用户信息
     * @param puin 用户ID
     * @param cookie 用户Cookie
     * @param onSuccess 成功回调，返回UserInfo对象
     * @param onError 错误回调
     */
    fun getUserInfo(
        puin: String,
        cookie: String,
        onSuccess: (UserInfo) -> Unit,
        onError: (String) -> Unit
    ) {
        val url = "${HttpApiConstants.PcUrls.base}/cgi-bin/petpk?cmd=viewattr&puin=$puin&kind=1"
        val headers = mapOf("Cookie" to cookie)

        HttpHelper.get(url, headers, object : IHttpCallback {
            override fun onSuccess(call: Call, response: Response) {
                val rawResponseBody = response.body?.string() ?: ""
                Log.d("UserInfoManager", "获取用户信息成功: $rawResponseBody")

                try {
                    // 处理responseBody，将",]"替换成"]"，修复数组最后一个元素的逗号问题
                    val responseBody = rawResponseBody.replace(Regex(",\\s*]"), "]")

                    // 解析JSON响应
                    val json = Json.Default.parseToJsonElement(responseBody).jsonObject
                    val result = json["result"]?.jsonPrimitive?.content

                    if (result == "0") {
                        // 请求成功，提取用户信息
                        val nickname = json["nickname"]?.jsonPrimitive?.content ?: ""

                        // 创建UserInfo对象
                        val userInfo = UserInfo(nickname = nickname)
                        onSuccess(userInfo)

                        Log.d("UserInfoManager", "解析用户信息成功: ${userInfo.nickname}")
                    } else {
                        val msg = json["msg"]?.jsonPrimitive?.content ?: "请求失败"
                        onError("请求失败: $msg")
                        Log.e("UserInfoManager", "请求失败: $msg")
                    }
                } catch (e: Exception) {
                    onError("解析失败: ${e.message}")
                    Log.e("UserInfoManager", "解析JSON失败: ${e.message}")
                }
            }

            override fun onFailure(call: Call, error: IOException) {
                onError("请求失败: ${error.message}")
                Log.e("UserInfoManager", "获取用户信息失败: ${error.message}")
            }
        })
    }
}